package com.xqy.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.ribbon.proxy.annotation.Hystrix;
import com.xqy.pojo.User;
import com.xqy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserController {
    @Autowired
    private DiscoveryClient client;
    @Autowired
    private UserService userService;
    // 获取注册进来的服务的一些信息 需要配合@EnableDiscoveryClient（标注在启动类上）
    @GetMapping("/dc")
    public  Object discovery(){
        List<String> services = client.getServices();
        System.out.println("discovery:services="+services);
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-USER");
        for (ServiceInstance serviceInstance :instances){
            System.out.println(
                    serviceInstance.getHost()+"\t"+
                            serviceInstance.getPort()+"\t"+
                            serviceInstance.getUri()+"\t"+
                            serviceInstance.getInstanceId());
        }
        return  this.client;
    }
    public  void  addUser(User user){
        userService.addUser(user);

    }
    @GetMapping("/get")
    public  User getUser(Integer userId){
        System.out.println("method: get");
        return userService.getUser(userId);
    }
//    @HystrixCommand(fallbackMethod = "getListFallBack")
    @GetMapping("/list")
    public  List<User> getList(){
        System.out.println("port:8001.List");
        return userService.getList();
    }
    public  List<User> getListFallBack(){
        System.out.println("port:8001.List.fallBack");
        User user = new User();
        user.setUserName("不存在此用户");
        List<User> list = new ArrayList<User>();
        list.add(user);
        return list;
    }
    @GetMapping("/test")
    public String getTest() {
        return "test consumer-hystrix";
    }
}